#include <vector>
#include <unordered_map>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
 * @lc app=leetcode.cn id=106 lang=cpp
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 递归大法好哇
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        unordered_map<int, int> mapper;
        for (int i = 0; i < inorder.size(); i++) mapper.insert({inorder[i], i});
        return buildTreeHelper(mapper, inorder, postorder, 0, inorder.size() - 1, 0, inorder.size() - 1);
    }

    TreeNode* buildTreeHelper(unordered_map<int, int>& mapper, vector<int>& inorder, vector<int>& postorder, int ip, int ie, int pp, int pe) {
        if (pe < pp) return nullptr;
        TreeNode *now = new TreeNode(postorder[pe]);
        int index = mapper[postorder[pe]];
        int lz = index - ip, rz = ie - index;
        now->right = buildTreeHelper(mapper, inorder, postorder, index + 1, ie, pe - rz, pe - 1);
        now->left = buildTreeHelper(mapper, inorder, postorder, ip, index - 1, pp, pe - rz - 1);
        return now;
    }

    // TODO:迭代思路
};
// @lc code=end

